<?php
/**
 * Created by PhpStorm.
 * User: Reborn
 * Date: 2019/12/5
 * Time: 10:38
 */
declare (strict_types = 1);

namespace app;

use app\common\exception\Http;
use think\exception\ValidateException;
use think\Validate;

abstract class BaseRequest extends Request
{
    /**
     * @var bool
     */
    public $batch = false;

    /**
     * @var string
     */
    protected $currentScene;

    /**
     * @var array
     */
    protected $scene = [];

    /**
     * @var array
     */
    protected $rule = [];

    /**
     * @var array
     */
    protected $message = [];

    /**
     * 指定场景验证
     *
     * @param string $scene
     *
     * @return $this
     */
    public function scene($scene)
    {
        $this->currentScene = $scene;

        return $this;
    }

    /**
     * 批量验证
     *
     * @param [type] $batch
     *
     * @return $this
     */
    public function batch($batch)
    {
        $this->batch = $batch;

        return $this;
    }

    /**
     * 验证数据
     * User Reborn
     * Time 2020/4/2 15:19
     * @param array $data
     * @return array
     * @throws Http
     */
    public function validate($data=[])
    {
        $newdata=[];
        try {
            $validate = new Validate();
            $validate->rule($this->rule);

            // 验证场景
            if ($this->currentScene) {
                $only = $this->scene[$this->currentScene];
                $validate->only($only);

                foreach ($only as $val){
                    if(isset($data[$val])){
                        $newdata[$val]=$data[$val];
                    }
                }
            }

            $validate->rule($this->rule)
                ->message($this->message)
                ->batch($this->batch)
                ->failException(true)
                ->check($data);
        } catch (ValidateException $e) {
            throw new Http($e->getMessage());
        }
        return $newdata;
    }

    /**
     * 获取请求数据
     * User Reborn
     * Time 2020/4/3 14:44
     * @param array $data
     * @param string $data
     * @param array $newdata
     * @return array
     */
    public function requestData(array $data,string $scene,array $newdata = [])
    {
        $only = $this->scene[$scene];
        foreach ($only as $val){
            if(isset($data[$val])){
                $newdata[$val]=$data[$val];
            }
        }
        return $newdata;
    }
}